<template>
<div class="login-form" v-loading="loading">
  <el-form
      ref="loginFormRef"
      :model="loginForm"
      status-icon
      :rules="rules"
      label-width="50px"
      class="loginForm"
  >
    <el-form-item label="账号" prop="username">
      <el-input v-model="loginForm.username" placeholder="请输入账号" />
    </el-form-item>
    <el-form-item label="密码" prop="password" type="password"
                  autocomplete="off">
      <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          autocomplete="off"
          @keyup.enter="submitForm(loginFormRef)"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(loginFormRef)"
      >登录</el-button
      >
      <el-button @click="resetForm(loginFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { toLogin } from '@/api/index'
import { useRouter } from 'vue-router'
export default {
  name: 'loginIndex',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const loginFormRef = ref<FormInstance>()
    const loginForm = reactive({
      username: 'jacky.zhang',
      password: 'infoweb'
    })
    const rules = reactive<FormRules>({
      username: [{ required: true, message: '不能为空', trigger: 'submit' }],
      password: [{ required: true, message: '不能为空', trigger: 'submit' }]
    })
    const Login = () => {
      const params: any = {
        grant_type: 'password',
        username: loginForm.username,
        password: loginForm.password,
        scope: 'ui',
        client_id: 'quectel',
        client_secret: 'quectel'
      }
      loading.value = true
      toLogin(params).then((res: any) => {
        // loading.value = false
        const data: any = res.data
        if(data.token_type && data.access_token) {
          localStorage.setItem('MINITOOLBOX_tk', `${data.token_type}${data.access_token}`)
          setTimeout(() => {
            router.replace({
              name: 'home'
            })
          })
        }
      }).catch(() => {
        loading.value = false
      })
    }
    const submitForm = (formEl: FormInstance | undefined) => {
      if(!formEl) return
      formEl.validate(valid => {
        if(valid) {
          Login()
        }
      })
    }
    const resetForm = (formEl: FormInstance | undefined) => {
      if(!formEl) return
      formEl.resetFields()
    }
    return {
      loginFormRef,
      loginForm,
      rules,
      loading,
      submitForm,
      resetForm
    }
  }
}
</script>

<style lang="scss" scoped>
.login-form {
  margin: 0 auto;
  width: 60%;
}
</style>
